#ifndef REMOTEGENERATOR_H
#define REMOTEGENERATOR_H

#include <QObject>
#include <QSocket>
#include <QTcpServer>

// HttpDaemon from http://doc.trolltech.com/solutions/3/qtservice/qtservice-example-server.html. Used for prototype purposes.

// HttpDaemon is the the class that implements the simple HTTP server.
class HttpDaemon : public QTcpServer
{
   Q_OBJECT
public:
   HttpDaemon( QObject* parent=0 ) :
       QTcpServer(8080,1,parent), disabled(FALSE)
   {
       if ( !ok() ) {
           qService->reportEvent( "Failed to bind to port 8080", QtService::Error );
           exit( 1 );
       }
   }

   void newConnection( int socket )
   {
       if ( disabled )
           return;

       // When a new client connects, the server constructs a QSocket and all
       // communication with the client is done over this QSocket. QSocket
       // works asynchronouslyl, this means that all the communication is done
       // in the two slots readClient() and discardClient().
       QSocket* s = new QSocket( this );
       connect( s, SIGNAL(readyRead()), this, SLOT(readClient()) );
       connect( s, SIGNAL(delayedCloseFinished()), this, SLOT(discardClient()) );
       s->setSocket( socket );

       qService->reportEvent( "New Connection" );
   }

   void pause()
   {
       disabled = TRUE;
   }

   void resume()
   {
       disabled = FALSE;
   }

private slots:
   void readClient()
   {
       if ( disabled )
           return;

       // This slot is called when the client sent data to the server. The
       // server looks if it was a get request and sends a very simple HTML
       // document back.
       QSocket* socket = (QSocket*)sender();
       if ( socket->canReadLine() ) {
           QStringList tokens = QStringList::split( QRegExp("[ \r\n][ \r\n]*"), socket->readLine() );
           if ( tokens[0] == "GET" ) {
               QTextStream os( socket );
               os.setEncoding( QTextStream::UnicodeUTF8 );
               os << "HTTP/1.0 200 Ok\r\n"
                   "Content-Type: text/html; charset=\"utf-8\"\r\n"
                   "\r\n"
                   "<h1>Nothing to see here</h1>\n";
               socket->close();

               qService->reportEvent( "Wrote to client" );
           }
       }
   }
   void discardClient()
   {
       QSocket* socket = (QSocket*)sender();
       delete socket;

       qService->reportEvent( "Connection closed" );
   }

private:
   bool disabled;
};


class RemoteGenerator : public QObject
{
Q_OBJECT
public:
    explicit RemoteGenerator(QObject *parent = 0);

signals:

public slots:

};

#endif // REMOTEGENERATOR_H
